package com.huangjue.backend.controller;

import com.huangjue.backend.dto.ConversationRequest;
import com.huangjue.backend.entity.AiProgrammingConversation;
import com.huangjue.backend.mapper.AiProgrammingConversationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/conversation")
@CrossOrigin(origins = "*") // 允许跨域请求
public class ConversationController {
    @Autowired
    private AiProgrammingConversationMapper aiProgrammingConversationMapper;

    @PostMapping("getConversation")
    public ResponseEntity<Map<String, Object>> getConversation(@RequestBody ConversationRequest request) {
        // 1. 统一非空校验
        if (!StringUtils.hasText(request.getUserId()) ||
                !StringUtils.hasText(request.getHomeworkId())) {
            return ResponseEntity.badRequest()
                    .body(Map.of("success", "false", "message", "userId 与 homeworkId 不能为空","data",null));
        }
        List<AiProgrammingConversation> aiProgrammingConversation = aiProgrammingConversationMapper.selectLatestConversations(request.getUserId(),request.getHomeworkId(),3);
        // 过滤逻辑：排除 userMessage 或 aiResponse 任一为空的对象
        List<AiProgrammingConversation> filteredList = aiProgrammingConversation.stream()
                .filter(conversation ->
                        // 检查 userMessage 非空（包含 null 和空字符串）
                        conversation.getUserMessage() != null &&
                                !conversation.getUserMessage().trim().isEmpty() &&

                                // 检查 aiResponse 非空（包含 null 和空字符串）
                                conversation.getAiResponse() != null &&
                                !conversation.getAiResponse().trim().isEmpty()
                )
                .collect(Collectors.toList());
        return ResponseEntity.ok(Map.of("success", "true", "message","获取记录成功","data", filteredList));
    }
}